import axios from 'axios'
import { message } from 'ant-design-vue'
import qs from 'qs'
import {getToken} from '@/utils/cache'
import useUserStore from '@/store/user'

const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL, // url = base url + request url
  timeout: 5000,
  withCredentials: true, // send cookies when cross-domain requests
})

// Request interceptors
service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    if (userStore?.token) {
      config.headers.Authorization = userStore?.token
    }
    if (config.method === 'get') {
      config.paramsSerializer = {
        serialize: (params) => {
          return qs.stringify(params, { arrayFormat: 'repeat' })
        },
      }
    }
    // 不缓存结果 解决ie刷新列表无数据更新
    config.headers['cache-control'] = 'no-cache'
    config.headers.Pragma = 'no-cache'
    return config
  },
  (error) => {
    Promise.reject(error)
  },
)

// Response interceptors
service.interceptors.response.use(
  (response) => {
    // 请求时如果带了这个参数且noError为true，就不显示请求失败的message弹窗。默认显示
    const noError = (response.config as any).noError || false
    // config带fullResponse且为true，则在请求成功时返回整个response。默认只返回result
    const fullResponse = (response.config as any).fullResponse || false
    // config带successMessage且为true，则在请求成功时显示成功信息的弹窗，默认不显示
    const successMessage = (response.config as any).successMessage || false

    const res = response.data

    const msg = res.result?.msg ?? (Array.isArray(res.result) ? res.result.join('，') : res.result) ?? res.msg
    // 超时处理
    if (res.code === 10008) {
      if (getToken()) {
        // 有token才提示
        message.error(msg,5)
      }
      setTimeout(() => {
        // UserModule.ResetToken()
        const href = res.result ? res.result : `${location.origin}/login`
        location.replace(href)
      }, 2500)
      return Promise.reject(res)
    }

    if (res.code !== 10000) {
      return Promise.reject(res)
    }
    else {
      if (successMessage) {
        message.success(msg)
      }
      return fullResponse ? res : res.result
    }
  },
  (error) => {
    // 网关请求400仍需取返回消息
    if (error?.response?.data?.code === 10006) {
      message.error(error?.response?.data?.result?.join(',') ?? error?.response?.data?.msg, 5)
      return Promise.reject(error)
    }
    else if (axios.isCancel(error)) {
      console.log('Request canceled', error.message)
    }
    else {
      message.error(error.message, 5)
      return Promise.reject(error)
    }
  },
)

export default service